package com.starpl.mobile.android.monthunsae.november.common;

import java.util.Date;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.starpl.mobile.android.platform.common.SharedUtil;
import com.starpl.mobile.android.platform.common.base.BaseApplication;

public class LocalPushReceiver extends BroadcastReceiver
{
	private static final String TAG = "LocalPushReceiver";
	
	@Override
	public void onReceive(Context context, Intent intent)
	{
		String action = intent.getAction();
		
		if(action.equals("android.intent.action.BOOT_COMPLETED"))
		{
			Log.i(TAG, "디바이스가 재부팅되어 월별운세 데이터를 복원합니다");
			String alarmList = SharedUtil.getInstance().getSharedPreference("alarmList");
			
			// 월별 운세 알람을 등록하기 위한 기본 작업
			LocalPushClient alarmClient = new LocalPushClient();
			
			try
			{
				JSONArray jsonAlarm = new JSONArray(alarmList);
				int alarmSize = jsonAlarm.length();
				
				for(int i = 0 ; i < alarmSize ; i++)
				{
					JSONObject object = (JSONObject) jsonAlarm.get(i);
					String date = object.getString("date");
					String message = object.getString("msg");
					
					// 알람 등록
					Date targetDate = new Date(Long.parseLong(date));
					alarmClient.setLocalPush(targetDate, message);
				}
			}
			catch(Exception e)
			{
				Log.e(TAG, e.getMessage());
			}
			
		}
		else if(action.equals(LocalPushClient.PUSH_ALARM_ACTION))
		{
			// 어플리케이션을 실행하기 위한 인텐트 생성
			Intent launcher = new Intent();
			launcher.setAction(intent.getStringExtra("p"));
			launcher.addCategory(Intent.CATEGORY_DEFAULT);
			
			// 팝업 윈도우 설정
			Class<?> pushClass = BaseApplication.getPushActivity();
			launcher = new Intent(context, pushClass);
			launcher.putExtras(intent);
			launcher.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(launcher);
		}
	}
}
